#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据合规检测探针SDK
提供敏感数据检测和合规性检查功能
"""

import requests
import json
from typing import Dict, Any, Optional


class DataComplianceDetector:
    """
    数据合规检测器
    用于检测文本中的敏感数据并进行合规性检查
    """

    def __init__(self, service_url: str = "http://go_service:8080"):
        """
        初始化数据合规检测器
        
        Args:
            service_url (str): 合规检测服务的URL地址
        """
        self.service_url = service_url

    def detect_sensitive_data(self, text: str) -> Dict[str, Any]:
        """
        检测文本中的敏感数据
        
        Args:
            text (str): 需要检测的文本
            
        Returns:
            dict: 检测结果，包含处理后的文本和发现的问题
        """
        try:
            response = requests.post(
                f"{self.service_url}/detect",
                json={"text": text},
                headers={"Content-Type": "application/json"},
                timeout=30
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": f"请求错误: {str(e)}"}
        except Exception as e:
            return {"error": f"未知错误: {str(e)}"}

    def check_compliance(self, text: str) -> Dict[str, Any]:
        """
        检查数据合规性
        
        Args:
            text (str): 需要检查的文本
            
        Returns:
            dict: 合规检查结果，包含是否合规和发现的问题
        """
        try:
            response = requests.post(
                f"{self.service_url}/compliance",
                json={"text": text},
                headers={"Content-Type": "application/json"},
                timeout=30
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": f"请求错误: {str(e)}"}
        except Exception as e:
            return {"error": f"未知错误: {str(e)}"}

    def process_data(self, text: str) -> Dict[str, Any]:
        """
        处理数据（检测+合规检查）
        
        Args:
            text (str): 需要处理的文本
            
        Returns:
            dict: 处理结果，包含检测和合规检查的所有信息
        """
        detection_result = self.detect_sensitive_data(text)
        compliance_result = self.check_compliance(text)
        
        return {
            "detection": detection_result,
            "compliance": compliance_result
        }


# 使用示例
if __name__ == "__main__":
    # 创建检测器实例
    detector = DataComplianceDetector("http://go_service:8080")
    
    # 测试文本
    test_text = "联系电话是13812345678，身份证号为110101199003077532"
    
    # 检测敏感数据
    detection_result = detector.detect_sensitive_data(test_text)
    print("敏感数据检测结果:", detection_result)
    
    # 合规检查
    compliance_result = detector.check_compliance(test_text)
    print("合规检查结果:", compliance_result)
    
    # 完整处理
    process_result = detector.process_data(test_text)
    print("完整处理结果:", process_result)